﻿using System.Security.Cryptography;
using System.Text;

namespace P2P.Util
{
    public class AESUtil
    {
        public static byte[] Encrypt(byte[] plainBuffer, string key)
        {
            using (Aes aes = Aes.Create())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);

                ICryptoTransform encryptor = aes.CreateEncryptor();

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                    {
                        cs.Write(plainBuffer,0, plainBuffer.Length);
                    }
                    return ms.ToArray();
                }
            }
        }

        public static byte[] Decrypt(byte[] encryptedBuffer, string key)
        {
            using (Aes aes = Aes.Create())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);

                ICryptoTransform decryptor = aes.CreateDecryptor();

                using (MemoryStream ms = new MemoryStream(encryptedBuffer))
                {
                    using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                    {
                        byte[] decryptedData = new byte[cs.Length];
                        cs.Read(decryptedData, 0, decryptedData.Length);
                        return decryptedData;
                    }
                }
            }
        }
    }
}
